package org.rulix.ogame.player.core.info;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.rulix.ogame.player.api.OgameFleetMovement;
import org.rulix.ogame.player.api.OgamePlanet;
import org.rulix.ogame.player.api.OgamePlanetCoordinates;
import org.rulix.ogame.player.core.OgameException;

public class OgameDataHelper {
	
	
	public static StringBuilder readInputStream(InputStream is){
		
		int b=-1;
		BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
		String line = null;
		StringBuilder sb = new StringBuilder();
		try {
			while ( null != (line = br.readLine())){
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return sb;
	}

	
	public List<OgamePlanet> getPlanets(StringBuilder planets) throws OgameException {
		Source planetsSource = new Source(planets.toString());
		
		List<Element> smallplanets = planetsSource.getAllElementsByClass("smallplanet");
		List<OgamePlanet> oPlanetList = Collections.synchronizedList(new ArrayList<OgamePlanet>());
		
		for (Element element : smallplanets) {

			OgamePlanet op = new OgamePlanet();
			Element first = element.getFirstElement(HTMLElementName.A);
			
			String valueHrefPlanet = first.getAttributeValue("href");
		
			try {
				List<NameValuePair> values = URLEncodedUtils.parse(new URI(valueHrefPlanet), null);
				for (NameValuePair nameValuePair : values) {
					if ( nameValuePair.getName().equals("cp")){
						op.setCode(nameValuePair.getValue());
					}
				}
			} catch (URISyntaxException e) {
				throw new OgameException(e.getMessage(), e);
			}

			
			first = element.getFirstElementByClass("planet-koords");
			String koords = first.getContent().toString();
			
			first = element.getFirstElementByClass("planet-name");
			String planetName = first.getContent().toString();
			
			op.setCoordinates(OgamePlanetCoordinates.getCoordinates(koords));
			op.setName(planetName);
			oPlanetList.add(op);
		}
		return oPlanetList;
	}
	
	public List<OgameFleetMovement> getFleetMovements(StringBuilder eventListData){
		Source eventListSource = new Source(eventListData.toString());
		
		List<Element> events = eventListSource.getAllElementsByClass("eventFleet");
		List<OgameFleetMovement> list = Collections.synchronizedList(new ArrayList<OgameFleetMovement>());
		
		
		for (Element event : events) {
			String arrivalStr = event.getFirstElementByClass("arrivalTime").getContent().toString();
			String coordsOrigin = event.getFirstElementByClass("coordsOrigin").getFirstElement("a").getContent().toString();
			String destCoords = event.getFirstElementByClass("destCoords").getFirstElement("a").getContent().toString();
			String missionFleet = event.getFirstElementByClass("missionFleet").getFirstElement("img").getAttributeValue("title");

			
			String[] aDate = arrivalStr.replaceAll("[^0-9:]", "").split(":");
			GregorianCalendar c = (GregorianCalendar)GregorianCalendar.getInstance();
			long currentMillis = c.getTimeInMillis();
			c.set(GregorianCalendar.HOUR_OF_DAY, Integer.parseInt(aDate[0]));
			c.set(GregorianCalendar.MINUTE, Integer.parseInt(aDate[1]));
			c.set(GregorianCalendar.SECOND, Integer.parseInt(aDate[2]));
			if (currentMillis > c.getTimeInMillis()){
				c.add(GregorianCalendar.HOUR_OF_DAY, 24);
			}
			
			OgameFleetMovement ofm = new OgameFleetMovement();
			ofm.setArrivalTime(c.getTimeInMillis());
			ofm.setOrigin(OgamePlanetCoordinates.getCoordinates(coordsOrigin));
			ofm.setTarget(OgamePlanetCoordinates.getCoordinates(destCoords));
			ofm.setMissionFromLocalizedString(missionFleet);
			list.add(ofm);
		}
		return list;
	}
	
	public void fetchPlanetResources(OgamePlanet ogamePlanet, StringBuilder planetData){
		
		Source planetsSource = new Source(planetData.toString());
		
		Element resourceMetal = planetsSource.getElementById("resources_metal");
		Element resourceCrystal = planetsSource.getElementById("resources_crystal");
		Element resourceDeuterium = planetsSource.getElementById("resources_deuterium");
		Element resourceEnergy = planetsSource.getElementById("resources_energy");
		Element resourceDarkMatter = planetsSource.getElementById("resources_darkmatter");
		ogamePlanet.setMetal(Integer.valueOf(resourceMetal.getContent().toString().trim().replaceAll("[^0-9]", "")));
		ogamePlanet.setCrystal(Integer.valueOf(resourceCrystal.getContent().toString().trim().replaceAll("[^0-9]", "")));
		ogamePlanet.setDeuterium(Integer.valueOf(resourceDeuterium.getContent().toString().trim().replaceAll("[^0-9]", "")));
		ogamePlanet.setEnergy(Integer.valueOf(resourceEnergy.getContent().toString().trim().replaceAll("[^0-9]", "")));
	}
	public void fetchPlanetBuildings(OgamePlanet ogamePlanet, StringBuilder planetData){
		
		Source planetsSource = new Source(planetData.toString());
		
		Element metal = planetsSource.getElementById("button1");
		Element crystal = planetsSource.getElementById("button2");
		Element deuterium = planetsSource.getElementById("button3");
		Element solar = planetsSource.getElementById("button4");
		Element fusion = planetsSource.getElementById("button5");
		Element satellite = planetsSource.getElementById("button6");
		Element metalSt = planetsSource.getElementById("button7");
		Element crystalSt = planetsSource.getElementById("button8");
		Element deuteriumSt = planetsSource.getElementById("button9");
		
		Element level = metal.getFirstElementByClass("level");
		ogamePlanet.setMetalMine(Integer.parseInt(level.getContent().toString().trim().replaceAll("[^0-9]", "")));
		
		level = crystal.getFirstElementByClass("level");
		ogamePlanet.setCrystalMine(Integer.parseInt(level.getContent().toString().trim().replaceAll("[^0-9]", "")));
		
		level = deuterium.getFirstElementByClass("level");
		ogamePlanet.setDeuteriumSynthesizer(Integer.parseInt(level.getContent().toString().trim().replaceAll("[^0-9]", "")));
		
		level = solar.getFirstElementByClass("level");
		ogamePlanet.setSolarPlant(Integer.parseInt(level.getContent().toString().trim().replaceAll("[^0-9]", "")));
		
		level = fusion.getFirstElementByClass("level");
		ogamePlanet.setFusionReactor(Integer.parseInt(level.getContent().toString().trim().replaceAll("[^0-9]", "")));
		
		level = satellite.getFirstElementByClass("level");
		ogamePlanet.setSolarSatellite(Integer.parseInt(level.getContent().toString().trim().replaceAll("[^0-9]", "")));
		
		level = metalSt.getFirstElementByClass("level");
		ogamePlanet.setMetalStorage(Integer.parseInt(level.getContent().toString().trim().replaceAll("[^0-9]", "")));
		
		level = crystalSt.getFirstElementByClass("level");
		ogamePlanet.setCrystalStorage(Integer.parseInt(level.getContent().toString().trim().replaceAll("[^0-9]", "")));
		
		level = deuteriumSt.getFirstElementByClass("level");
		ogamePlanet.setDeuteriumTank(Integer.parseInt(level.getContent().toString().trim().replaceAll("[^0-9]", "")));
		
	}
	
	public void fetchPlanetTechnology(OgamePlanet ogamePlanet, StringBuilder planetData){
		
	}
	
	public void fetchPlanetFleet(OgamePlanet ogamePlanet, StringBuilder planetData){
		
	}
	
	public void fetchPlanetDefenses(OgamePlanet ogamePlanet, StringBuffer planetData){
		
	}
	
	
	
	
}
